package bfa.cps.connectivity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

public class ConnectivityReceiver extends BroadcastReceiver{

	public Handler handler=null;
	Bundle b = new Bundle();
	
	
	public static String  CR_KEY="connectivity";
	
	public static String  CR_CONNECTED="Connected";
	public static String  CR_CONNECTING="Connecting";
	public static String  CR_DISCONNECTED="Disconnected";
	public static String  CR_DISCONNECTING="Disconnecting";
	public static String  CR_SUSPENDED="Suspended";
	public static String  CR_UNKNOWN="Unknown";

	private String getNetworkStateString(NetworkInfo.State state){
    	String stateString = "Unknown";
    	
    	switch(state)
    	{
    		case CONNECTED:		stateString = CR_CONNECTED; 		break;
    		case CONNECTING:	stateString = CR_CONNECTING; 	break;
    		case DISCONNECTED:	stateString = CR_DISCONNECTED; 	break;
    		case DISCONNECTING:	stateString = CR_DISCONNECTING; 	break;
    		case SUSPENDED:		stateString = CR_SUSPENDED; 		break;
    		default:			stateString = CR_UNKNOWN; 		break;
    	}
    	
    	return stateString;
    }
	
	@Override
	public void onReceive(Context context, Intent intent) {
		NetworkInfo info = intent.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);
		
		if(null != info) {
			String state = getNetworkStateString(info.getState());
			//String stateString = info.toString().replace(',', '\n');
			
//			String infoString = String.format("Network Type: %s\nNetwork State: %s\n\n%s",
//					info.getTypeName(),state,stateString);
			
			Log.i("ConnTest",info.getTypeName());
			Log.i("ConnTest",state);
			Log.i("ConnTest",info.toString());
			
			mandaMessaggio(CR_KEY,state);
			//txtNetworkInfo.setText(infoString);
		}
	}
	
	private void mandaMessaggio(String key,String valore) {
		if (handler!=null) {	
		    Message msg = handler.obtainMessage();
		    b.putString(key,valore);
		    msg.setData(b);
		    handler.sendMessage(msg);
		 }
	}
	
}
